<script setup lang="ts">
import useDragramStore from '../../../store/useDragramStore'

const model = defineModel<boolean>()

const fileTree = ref<DirectoryTree>()
const defaultExpandKeys = ref<string[]>([])
const getProjectFileTree = async () => {
  const res = await $fetch<ResBodyType>('/api/file/filetree', {
    method: 'get'
  })
  if (res.status === 200) {
    console.log('getProjectFileTree', res)
    fileTree.value = res.body
    pickDefaultExpandKeys(res.body)
  }
}
// 提取默认展开的节点
const pickDefaultExpandKeys = (data: DirectoryTree) => {
  if (data.name === 'views') {
    defaultExpandKeys.value.push(data.id)
  }
  // 递归遍历树结构
  if (data.children && data.children.length > 0) {
    for (const child of data.children) {
      pickDefaultExpandKeys(child)
    }
  }
}

watchEffect(() => {
  // console.log(model.value)
  if (model.value) {
    console.log('model.value', model.value)
    getProjectFileTree()
  }
})

const treeProps = {
  children: 'children',
  label: 'name'
}

// 新增
const dragramStore = useDragramStore()
const createLoading = ref(false)
const append = async (data: DirectoryTree) => {
  // 生成文件内容
  try {
    const pageContent = dragramStore.getPageFileContent()
    if (!pageContent) {
      return
    }
    const res = await $fetch<ResBodyType>('/api/file/create_view', {
      method: 'POST',
      body: {
        fileName: dragramStore.fileName,
        fileContent: pageContent,
        filePath: data.path,
        interactionElements: dragramStore.interactionElements
      }
    })
    if (res.status === 200) {
      ElMessage.success('页面创建成功')
      getProjectFileTree()
    } else {
      console.log(res)
      ElMessage.error(res.message)
    }
  } catch (error: any) {
    ElMessage.error(error.message)
  } finally {
    createLoading.value = false
  }
}

// 关闭弹窗
const close = () => {
  model.value = false
}
</script>

<template>
  <el-dialog title="请选择文件存放目录" width="500" v-model="model" :z-index="2000">
    <div v-if="fileTree">
      <el-tree
        node-key="id"
        :data="[fileTree]"
        :props="treeProps"
        :default-expanded-keys="defaultExpandKeys"
        empty-text="工程文件扫描失败，请重新打开"
      >
        <template #default="{ node, data }">
          <span class="custom-tree-node" v-if="data">
            <span> {{ data.type === 'directory' ? '📂' : '📜' }} {{ node.label }}</span>
            <span>
              <el-button
                v-if="
                  data.type === 'directory' && data.name === 'views' && data.level !== 0
                "
                link
                type="primary"
                @click.stop="append(data)"
                :loading="createLoading"
              >
                新增页面
              </el-button>
            </span>
          </span>
        </template>
      </el-tree>
    </div>

    <template #footer>
      <el-button type="success" icon="ChromeFilled" @click="close">确认应用</el-button>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped></style>
<style>
.custom-tree-node {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 14px;
  padding-right: 8px;
}
</style>
